home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 15445 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  44 lines

  1. Newsgroups: comp.lang.c
  2. Path: netcom.com!smryan
  3. From: smryan@netcom.com (@#$%!?!)
  4. Subject: Re: double-->float... number changes
  5. Message-ID: <smryanDq1MEJ.25B@netcom.com>
  6. Organization: The Programmer formerly known as S M Ryan
  7. X-Newsreader: TIN [version 1.2 PL1]
  8. References: <4l3olr$85o@news.magi.com>
  9. Date: Thu, 18 Apr 1996 05:39:55 GMT
  10. Sender: smryan@netcom12.netcom.com
  11.  
  12. : I have a number (that I pick up from Sybase), declared as a double,
  13. : it's value is 123.4, I then want to store it in a float variable, but
  14. : the number changes to 123.399994.
  15.  
  16. .4 cannot be exactly represented in binary, the presumed radix of any
  17. floating-point type, so truncating trailing bits replaces one inexact
  18. representation with another, even less exact, representation. At some
  19. point the effects are bound to be noticeable.
  20.  
  21. : This messes up calculations later on in program.
  22. : I tried converting the number to a string and using atof() to get a
  23. : float number, but this function returns a double?!, and the subsequent
  24. : conversion to a float produces the same error.
  25.  
  26. : Is there a way to get 123.4 when converting to a float number?
  27.  
  28. You can round fractional digits. If you want to round x to 2 decimal
  29. places, one possible code is
  30.  
  31.     x = ((long)(x*100+.5))/100.0;
  32.  
  33. There are others, perhaps already available in your friendly
  34. neighbourhood math library.
  35.  
  36. And depending on the range of values and their operations, you can
  37. do it all in integers with implicit decimal points (like Cobol).
  38.  
  39. -- 
  40. The Queen who loves, the Queen of life,    | smryan@netcom.com  PO Box 1563
  41. the Queen who straits, the Queen of strife;|          Cupertino, California
  42. with gasp of death or gift of breath       | (xxx)xxx-xxxx            95015
  43. she brings the choice of birth or knife.   |         I don't use no smileys
  44.